<template>
  <div class="manager-container">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">
          <i class="el-icon-user"></i>
          区域管理员管理
        </h1>
        <p class="page-subtitle">管理社区内的所有区域管理员信息</p>
      </div>
      <el-button type="primary" size="large" @click="openDialog()" class="add-btn">
        <i class="el-icon-plus"></i>
        新增管理员
      </el-button>
    </div>

    <!-- 统计卡片区域 -->
    <div class="stats-container">
      <div class="stat-card" v-for="(stat, index) in stats" :key="index">
        <div class="stat-icon" :style="{ backgroundColor: stat.color }">
          <i :class="stat.icon"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ stat.value }}</div>
          <div class="stat-label">{{ stat.label }}</div>
        </div>
      </div>
    </div>

    <!-- 管理员卡片网格 -->
    <div class="managers-grid">
      <div 
        v-for="manager in tableData" 
        :key="manager.id" 
        class="manager-card"
        @click="openDialog(manager)"
      >
        <div class="manager-avatar">
          <img v-if="manager.avatarUrl" :src="manager.avatarUrl" alt="头像" />
          <div v-else class="avatar-placeholder">
            <i class="el-icon-user"></i>
          </div>
        </div>
        <div class="manager-info">
          <h3 class="manager-name">{{ manager.amName }}</h3>
          <div class="manager-details">
            <div class="detail-item">
              <i class="el-icon-phone"></i>
              <span>{{ manager.amPhone }}</span>
            </div>
            <div class="detail-item">
              <i class="el-icon-user"></i>
              <span>{{ manager.amSex }}</span>
            </div>
            <div class="detail-item">
              <i class="el-icon-suitcase"></i>
              <span>{{ manager.amComment }}</span>
            </div>
            <div class="detail-item">
              <i class="el-icon-date"></i>
              <span>{{ formatDateTime(manager, null, manager.joinYear) }}</span>
            </div>
          </div>
          <div class="manager-actions">
            <el-button size="small" type="primary" @click.stop="openDialog(manager)">
              <i class="el-icon-edit"></i>
              编辑
            </el-button>
            <el-button size="small" type="danger" @click.stop="handleDelete(manager.id)">
              <i class="el-icon-delete"></i>
              删除
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页器 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="prev, pager, next, jumper, ->, total"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" class="manager-dialog">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="manager-form"
      >
        <el-form-item label="姓名" prop="amName">
          <el-input v-model="form.amName" />
        </el-form-item>
        <el-form-item label="电话" prop="amPhone">
          <el-input v-model="form.amPhone" />
        </el-form-item>
        <el-form-item label="性别" prop="amSex">
          <el-select v-model="form.amSex" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职位" prop="amComment">
          <el-input v-model="form.amComment" />
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            :auto-upload="false"
            :show-file-list="false"
            @change="handleFileChange"
            :before-upload="beforeUpload"
          >
            <img v-if="form.avatarUrl" :src="form.avatarUrl" class="avatar" style="width: 100px; height: 100px; object-fit: cover; border: 3px solid #42b983; border-radius: 8px; box-shadow: 0 4px 8px rgba(66, 185, 131, 0.2);">
            <div v-else class="avatar-uploader-icon">
              <Plus style="font-size: 24px;" />
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="工作时间" prop="joinYear">
          <el-date-picker
            v-model="form.joinYear"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="选择日期"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { postRequest, deleteRequest } from '@/utils/request';

const tableData = ref([]);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
const dialogVisible = ref(false);
const dialogTitle = ref('新增区域管理员');
const formRef = ref(null); // 添加formRef声明
const avatarFile = ref(null);
const rules = ref({
  amName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  amPhone: [{ required: true, message: '请输入电话', trigger: 'blur' }],
  amSex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  amComment: [{ required: true, message: '请输入职位', trigger: 'blur' }],
  joinYear: [{ required: true, message: '请选择工作时间', trigger: 'change' }]
});
const form = reactive({
  id: null,
  amName: '',
  amPhone: '',
  amSex: '',
  amComment: '',
  avatarUrl: '',
  joinYear: ''
});

function fetchData() {
  postRequest('/areaManager/getAreaManagerByPage', { current: currentPage.value, size: pageSize.value }).then(res => {
    if (res && res.data && res.data.data) {
      tableData.value = Array.isArray(res.data.data.areaManager) ? res.data.data.areaManager : [];
      total.value = res.data.data.total || 0;
    } else {
      tableData.value = [];
      total.value = 0;
    }
  }).catch(error => {
    console.error('获取数据失败:', error);
    tableData.value = [];
    total.value = 0;
  });
}

// 删除未使用的handleUploadSuccess函数
// 删除未使用的beforeAvatarUpload函数
function openDialog(row) {
  if (row) {
      dialogTitle.value = '编辑区域管理员';
      Object.assign(form, row);
      // 格式化日期为yyyy-MM-dd
      if (row.joinYear) {
        const date = new Date(row.joinYear);
        if (!isNaN(date.getTime())) {
          form.joinYear = date.toISOString().split('T')[0];
        } else {
          form.joinYear = '';
        }
      }
    } else {
    dialogTitle.value = '新增区域管理员';
    form.id = null;
    form.amName = '';
    form.amPhone = '';
    form.amSex = '';
    form.amComment = '';
    // form.avatarUrl = '';
    form.joinYear = '';
  }
  dialogVisible.value = true;
}

const handleFileChange = (file) => {
  avatarFile.value = file.raw;
  const reader = new FileReader();
  const localForm = form; // Capture form reference
  reader.onload = (e) => {
    localForm.avatarUrl = e.target.result;
  };
  reader.readAsDataURL(file.raw);
};

function beforeUpload(file) {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!');
  }
  return isJPG && isLt2M;
}

const handleSubmit = async () => {
  if (!formRef.value) {
    ElMessage.error('表单引用未找到');
    return;
  }
  
  try {
    const valid = await formRef.value.validate();
    if (valid) {
      // 第一步：提交区域管理员信息（不包含文件）
      const areaManagerData = {
        id: form.id,
        amName: form.amName,
        amPhone: form.amPhone,
        amSex: form.amSex,
        amComment: form.amComment,
        joinYear: form.joinYear,
        avatarUrl: !!avatarFile.value // 有新文件为true，否则为false
      };
      
      let response;
      if (form.id) {
        // 编辑模式
        response = await postRequest('/areaManager/updateAreaManagerById', areaManagerData);
      } else {
        // 添加模式
        response = await postRequest('/areaManager/addAreaManager', areaManagerData);
      }
      
      if (response.data.code === 200) {
        // 第二步：如果有文件，单独上传文件
        if (avatarFile.value) {
          const fileFormData = new FormData();
          fileFormData.append('avatar', avatarFile.value);
          
          // 获取新增或更新的区域管理员ID
          const amId = form.id || response.data.data; // 如果是新增，从响应中获取ID
          fileFormData.append('amId', amId);
          
          // 上传文件
          const fileResponse = await postRequest('/file/upload', fileFormData);
          if (fileResponse.data.code !== 200) {
            ElMessage.warning('区域管理员信息保存成功，但头像上传失败');
          }
        }
        
        ElMessage.success(form.id ? '更新成功' : '添加成功');
        dialogVisible.value = false;
        fetchData();
        // 重置文件状态
        avatarFile.value = null;
        // 重置表单
        formRef.value.resetFields();
      } else {
        ElMessage.error(response.data.msg || (form.id ? '更新失败' : '添加失败'));
      }
    }
  } catch (error) {
    console.error('表单提交失败:', error);
    ElMessage.error('请求失败: ' + error.message);
  }
};

function handleDelete(id) {
  ElMessageBox.confirm('确定要删除该区域管理员吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteRequest(`/areaManager/deleteAreaManagerById/${id}`).then(() => {
      ElMessage.success('删除成功');
      fetchData();
    });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
}
const formatDateTime = (row, column, value) => {
  if (!value) return '';
  // 将ISO时间格式转换为'YYYY-MM-DD HH:mm:ss'格式
  const date = new Date(value);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
};
function handlePageChange(page) {
  currentPage.value = page;
  fetchData();
}

// 统计数据
const stats = computed(() => [
  {
    label: '总管理员数',
    value: total.value,
    icon: 'el-icon-user',
    color: '#409EFF'
  },
  {
    label: '男',
    value: tableData.value.filter(m => m.amSex === '男').length,
    icon: 'el-icon-male',
    color: '#67C23A'
  },
  {
    label: '女',
    value: tableData.value.filter(m => m.amSex === '女').length,
    icon: 'el-icon-female',
    color: '#E6A23C'
  }
]);

onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.manager-container {
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  background: rgba(255, 255, 255, 0.95);
  padding: 20px 30px;
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

.header-content {
  flex: 1;
}

.page-title {
  margin: 0 0 5px 0;
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
  display: flex;
  align-items: center;
  gap: 10px;
}

.page-subtitle {
  margin: 0;
  color: #7f8c8d;
  font-size: 16px;
}

.add-btn {
  background: linear-gradient(45deg, #667eea, #764ba2);
  border: none;
  padding: 12px 24px;
  border-radius: 25px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.add-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 10px 25px rgba(102, 126, 234, 0.4);
}

.stats-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  background: rgba(255, 255, 255, 0.95);
  padding: 20px;
  border-radius: 15px;
  display: flex;
  align-items: center;
  gap: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 40px rgba(0, 0, 0, 0.15);
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  color: #2c3e50;
  margin-bottom: 5px;
}

.stat-label {
  color: #7f8c8d;
  font-size: 14px;
}

.managers-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 25px;
  margin-bottom: 30px;
}

.manager-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 25px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: center;
  gap: 20px;
}

.manager-card:hover {
  transform: translateY(-10px) scale(1.02);
  box-shadow: 0 20px 50px rgba(0, 0, 0, 0.2);
}

.manager-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}

.manager-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #bdbdbd;
  font-size: 36px;
}

.manager-info {
  flex: 1;
  text-align: left;
}

.manager-name {
  margin: 0 0 10px 0;
  font-size: 20px;
  font-weight: 700;
  color: #2c3e50;
}

.manager-details {
  margin-bottom: 15px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 6px;
  color: #7f8c8d;
  font-size: 14px;
}

.manager-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.manager-dialog {
  border-radius: 15px;
}

.manager-form {
  padding: 20px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 20px;
    text-align: center;
  }
  .stats-container {
    grid-template-columns: repeat(2, 1fr);
  }
  .managers-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 480px) {
  .stats-container {
    grid-template-columns: 1fr;
  }
  .manager-card {
    padding: 20px;
  }
}
</style>

<style>
.table-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #38bdf8;
}

</style>

<style scoped>
::v-deep .avatar-uploader .el-upload {
  display: block;
  width: 100px;
  height: 100px;
}
.avatar-uploader-icon {
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #42b983;
  background-color: #f5f7fa;
  border: 1px dashed #ccc;
  border-radius: 8px;
}
</style>